package cn.kz.hrm.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 配置拦截器
 */
@Configuration
public class DefaultOAuth2FeignRequestInterceptor implements RequestInterceptor{

    //前台访问后台传递请求头
    private static final String AUTHORIZATION_HEADER = "Authorization";

    /**
     * feign的跨服务的访问是依靠requestTemplate代理访问，
     * 所以在他的请求中进行设置token，因为同服务之间的访问是相同的token
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //获取请求头的对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //获取请求头
        String requestHeader = request.getHeader(AUTHORIZATION_HEADER);

        //将获取到的请求头中的信息放置到feign的请求头中
        requestTemplate.header(AUTHORIZATION_HEADER, requestHeader);
    }
}
